package com.ktjiaoyu.server.security;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

/**
 * spring security 配置
 */
@Configuration
// 开启基于注解的权限控制方案
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private JwtAuthenticationTokenFilter jwtAuthenticationTokenFilter;

    @Autowired
    private AccessDeniedHandlerImpl AccessDeniedHandler;

    @Autowired
    private AuthenticationEntryPointImpl authenticationEntryPointImpl;

    @Override
    protected void configure(HttpSecurity http) throws Exception {

        // 关闭csrf 跨站请求伪造,前后端分离项目 就得 关闭
        http.csrf().disable();

        //禁用springsecurity的会话管理
        http.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);

        // 给相关请求放行
        http.authorizeRequests()
                .antMatchers("/doLogin"
                        ,"/doc.html"
                        ,"/webjars/**"
                        ,"/swagger-resources/**"
                        ,"/v2/api-docs/**"
                        ,"/captcha"
                )
                .permitAll();

        // 任何请求都要认证才能访问
        http.authorizeRequests((requests) -> requests.anyRequest().authenticated());

        // 把token校验过滤器添加到过滤器链中
        http.addFilterBefore(jwtAuthenticationTokenFilter, UsernamePasswordAuthenticationFilter.class);

        // 设置 授权异常和认证异常实现方式
        http.exceptionHandling().accessDeniedHandler(AccessDeniedHandler).authenticationEntryPoint(authenticationEntryPointImpl);
    }

    /**
     * 登录时需要AuthenticationManager对象，正好父类有提供
     * @return
     * @throws Exception
     */
    @Bean
    @Override
    protected AuthenticationManager authenticationManager() throws Exception {
        return super.authenticationManager();
    }
    /**
     * 密码加密
     * @return
     */
    @Bean
    public PasswordEncoder passwordEncoder(){
        return new BCryptPasswordEncoder();
    }
}
